package finance

import (
	"encoding/csv"
	"fmt"
	"os"
	"time"

	"github.com/gin-gonic/gin"
	"go-papers/models"
	"go-papers/pkg/lognew"
	"go-papers/tools"
	"go-papers/tools/app"
)

func OrganCourse(c *gin.Context) {
	var data models.Course
	var err error
	var pageSize = 10
	var pageIndex = 1

	if size := c.Request.FormValue("pageSize"); size != "" {
		pageSize = tools.StrToInt(err, size)
	}
	if index := c.Request.FormValue("pageIndex"); index != "" {
		pageIndex = tools.StrToInt(err, index)
	}

	if index := c.Request.FormValue("courseId"); index != "" {
		data.CourseId = tools.StrToInt(err, index)
	}
	if index := c.Request.FormValue("organId"); index != "" {
		data.OrganId = tools.StrToInt(err, index)
	}
	data.CourseStatus = c.Request.FormValue("courseStatus")
	data.CourseName = c.Request.FormValue("courseName")
	data.CourseImg = c.Request.FormValue("courseImg")
	data.CourseType = c.Request.FormValue("courseType")
	data.CourseCategory = c.Request.FormValue("courseCategory")
	data.OrganName = c.Request.FormValue("organName")
	data.BrandName = c.Request.FormValue("brandName")
	data.CourseTeach = c.Request.FormValue("courseTeach")
	if index := c.Request.FormValue("coursePrice"); index != "" {
		data.CoursePrice = tools.StringToFloat64(err, index)
	}
	if index := c.Request.FormValue("discountPrice"); index != "" {
		data.DiscountPrice = tools.StringToFloat64(err, index)
	}
	data.CourseTime = c.Request.FormValue("courseTime")
	data.CourseAge = c.Request.FormValue("courseAge")
	data.UpdateStart = c.Request.FormValue("updateStart")
	data.UpdateEnd = c.Request.FormValue("updateEnd")

	data.DataScope = tools.GetUserIdStr(c)
	result, count, err := data.GetFiancePage(pageSize, pageIndex) //OrganCourse 机构财务管理
	if err != nil {
		app.ApiResp(c, -1, "数据操作失败："+err.Error(), nil)
		return
	}
	app.PageOK(c, result, count, pageIndex, pageSize, "")
}

func OrganOrder(c *gin.Context) {
	var data models.Order
	var err error
	var pageSize = 100
	var pageIndex = 1

	if size := c.Request.FormValue("pageSize"); size != "" {
		pageSize = tools.StrToInt(err, size)
	}
	if index := c.Request.FormValue("pageIndex"); index != "" {
		pageIndex = tools.StrToInt(err, index)
	}

	data.OrderNo = c.Request.FormValue("orderNo")
	data.OrderName = c.Request.FormValue("orderName")
	data.OrderStatus = c.Request.FormValue("orderStatus")

	if index := c.Request.FormValue("memberId"); index != "" {
		data.MemberId = tools.StrToInt(err, index)
	}
	if index := c.Request.FormValue("memberMomId"); index != "" {
		data.MemberMomId = tools.StrToInt(err, index)
	}
	if index := c.Request.FormValue("courseId"); index != "" {
		data.CourseId = tools.StrToInt(err, index)
	}
	data.MemberPhone = c.Request.FormValue("memberPhone")
	data.MemberName = c.Request.FormValue("memberName")

	data.PayType = c.Request.FormValue("payType")
	data.PayNo = c.Request.FormValue("payNo")
	data.PayTime = c.Request.FormValue("payTime")

	//"isSure": "1",  // 订单是否 确认排课
	//sureTime
	data.SureTimeStart = c.Request.FormValue("sureTimeStart")
	data.SureTimeEnd = c.Request.FormValue("sureTimeEnd")
	//"isShare": "1", // 订单是否结算
	//shareTime
	data.ShareTimeStart = c.Request.FormValue("shareTimeStart")
	data.ShareTimeEnd = c.Request.FormValue("shareTimeEnd")

	data.IsSure = c.Request.FormValue("isSure")
	data.IsShare = c.Request.FormValue("isShare")
	//organOrder
	data.AddressSearch = c.Request.FormValue("addressSearch") //所在地区
	if data.AddressSearch == "" {
		// studentAddr
		data.AddressSearch = c.Request.FormValue("studentAddr") //所在地区
	}

	//addressText studentAddress
	//data.StudentAddr = c.Request.FormValue("studentAddress") //所在地区

	data.Address = c.Request.FormValue("address") //小区名称
	if data.Address == "" {
		data.Address = c.Request.FormValue("studentAddress")
	}
	data.OrganName = c.Request.FormValue("organName")   //机构名称
	data.BrandName = c.Request.FormValue("brandName")   //品牌名称
	data.CourseName = c.Request.FormValue("courseName") //课程名称

	data.PayTimeStart = c.Request.FormValue("payTimeStart")
	data.PayTimeEnd = c.Request.FormValue("payTimeEnd")

	data.DataScope = tools.GetUserIdStr(c)

	//lognew.Info(c, "GetFiancePageReq", lognew.Fields{"search": data})
	result, count, err := data.GetFiancePage(pageSize, pageIndex)
	if err != nil {
		app.ApiResp(c, -1, "数据操作失败："+err.Error(), nil)
		return
	}

	if len(result) > 0 {
		//
		for i := 0; i < len(result); i++ {

			price := result[i].ShareMomOrganPrice + result[i].ShareMomMemberPrice

			// 状态
			//result[i].IsSure = isSure
			//result[i].IsShare = isShare
			result[i].MomSharePrice = price

		}
	}
	app.PageOK(c, result, count, pageIndex, pageSize, "")
}

type OrganSureReq struct {
	OrganId int `json:"organ_Id"`
	OrderId int `json:"order_id"`
}

func OrganSure(c *gin.Context) {
	var data models.Order
	var err error

	rt := &OrganSureReq{}
	if e := c.ShouldBind(rt); e != nil {
		app.CommonResp(c, -1, "数据解析异常:"+e.Error(), data)
		return
	} else {
		data.OrganId = rt.OrganId
		data.OrderId = rt.OrderId
	}
	// 二次解析
	if data.OrganId == 0 {
		if index := c.Request.FormValue("organ_id"); index != "" {
			data.OrganId = tools.StrToInt(err, index)
		}
		if index := c.Request.FormValue("order_id"); index != "" {
			data.OrderId = tools.StrToInt(err, index)
		}
	}

	if data.OrganId == 0 || data.OrderId == 0 {
		app.CommonResp(c, -1, "数据解析异常/organ_id/order_id", data)
		return
	}

	orderInfo, _ := data.GetByID(data.OrderId)
	if orderInfo.OrderId == 0 {
		app.CommonResp(c, -1, "订单信息未查询到", orderInfo)
		return
	}

	if orderInfo.IsShare == "1" {
		app.CommonResp(c, -1, "订单已经结算", orderInfo)
		return
	}

	// 进行订单状态修改
	err = data.UpdateSure(data.OrderId, data.OrganId)
	if err != nil {
		lognew.Error(c, "UpdateSure", lognew.Fields{"err": err.Error(), "orderInfo": orderInfo})
	}
	app.CommonResp(c, 0, "订单结算", orderInfo)
	return
}

// DownOrderList
func DownFianceOrganOrder(c *gin.Context) {
	var data models.Order
	var err error
	var pageSize = 100
	var pageIndex = 1

	if size := c.Request.FormValue("pageSize"); size != "" {
		pageSize = tools.StrToInt(err, size)
	}
	if index := c.Request.FormValue("pageIndex"); index != "" {
		pageIndex = tools.StrToInt(err, index)
	}

	data.OrderNo = c.Request.FormValue("orderNo")
	data.OrderName = c.Request.FormValue("orderName")
	data.OrderStatus = c.Request.FormValue("orderStatus")

	if index := c.Request.FormValue("memberId"); index != "" {
		data.MemberId = tools.StrToInt(err, index)
	}
	if index := c.Request.FormValue("memberMomId"); index != "" {
		data.MemberMomId = tools.StrToInt(err, index)
	}
	if index := c.Request.FormValue("courseId"); index != "" {
		data.CourseId = tools.StrToInt(err, index)
	}
	if index := c.Request.FormValue("organId"); index != "" {
		data.OrganId = tools.StrToInt(err, index)
	}
	data.MemberPhone = c.Request.FormValue("memberPhone")
	data.MemberName = c.Request.FormValue("memberName")

	data.PayType = c.Request.FormValue("payType")
	data.PayNo = c.Request.FormValue("payNo")
	data.PayTime = c.Request.FormValue("payTime")

	data.AddressSearch = c.Request.FormValue("addressSearch") //所在地区
	data.Address = c.Request.FormValue("address")             //小区名称
	data.OrganName = c.Request.FormValue("organName")         //机构名称
	data.BrandName = c.Request.FormValue("brandName")         //品牌名称

	data.PayTimeStart = c.Request.FormValue("payTimeStart")
	data.PayTimeEnd = c.Request.FormValue("payTimeEnd")
	data.DataScope = tools.GetUserIdStr(c)
	result, count, err := data.GetFiancePage(pageSize, pageIndex)
	if err != nil {
		app.ApiResp(c, -1, "数据操作失败："+err.Error(), nil)
		return
	}

	header := []string{"品牌名称", "机构名称", "课程名称", "订单编号", "会员姓名", "会员ID", "订单金额", "订单状态",
		"支付时间", "所在地区", "是否排课", "是否结算", "结算状态", "结算时间", "课程佣金"} //标题
	cellist := [][]string{
		header,
	}
	cellist = DataToStringV8(result, cellist)

	page := count/pageSize + 1

	for i := 2; i <= page; i++ {
		pageIndex = i
		result, _, _ = data.GetFiancePage(pageSize, pageIndex)
		if len(result) <= 0 {
			break
		}
		cellist = DataToStringV8(result, cellist)
	}

	// 创建文件
	filepath := "static/"
	filename := "FianceOrganOrder_" + time.Now().Format("20060102150405") + ".csv"
	newFile, err := os.Create(filepath + filename)
	if err != nil {
		app.OK(c, nil, err.Error())
		return
	}
	defer func() {
		newFile.Close()

		err := os.Remove(filepath + filename)
		if err != nil {
			// 删除失败
			lognew.Info(c, "导出文件-清理失败", lognew.Fields{"file": filepath + filename, "err": err.Error()})
		}

	}()

	// 写入UTF-8
	newFile.WriteString("\xEF\xBB\xBF") // 写入UTF-8 BOM，防止中文乱码
	// 写数据到csv文件
	w := csv.NewWriter(newFile)
	// WriteAll方法使用Write方法向w写入多条记录，并在最后调用Flush方法清空缓存。
	w.WriteAll(cellist)
	w.Flush()

	c.File(filepath + filename)

}

// OrganTeacher
// {"品牌名称", "机构名称", "课程名称", "订单编号", "会员姓名", "会员ID", "订单金额", "订单状态",
//   "支付时间", "所在地区", "是否排课", "是否结算", "结算状态", "结算时间", "课程佣金"} //标题
func DataToStringV8(list []models.OrderFiance, data [][]string) [][]string {
	for i := 0; i < len(list); i++ {
		op := fmt.Sprintf("%.2f", list[i].OrderPrice)
		price := list[i].ShareMomOrganPrice + list[i].ShareMomMemberPrice
		context := []string{
			list[i].BrandName,
			list[i].OrganName,
			list[i].CourseName,
			list[i].OrderNo,
			list[i].MemberName,
			tools.IntToString(list[i].MemberId),
			op,
			tools.OrderStatusName(list[i].OrderStatus),
			list[i].PayTime,
			list[i].StudentAddr,
			list[i].IsSure,
			list[i].IsShare,
			list[i].ShareTime,
			tools.ShareStatusName(list[i].OrderStatus),
			tools.Float64ToStringV2(price),
		}
		data = append(data, context)
	}
	return data
}

func DownFianceOrganCourse(c *gin.Context) {
	var data models.Course
	var err error
	var pageSize = 100
	var pageIndex = 1

	if size := c.Request.FormValue("pageSize"); size != "" {
		pageSize = tools.StrToInt(err, size)
	}
	if index := c.Request.FormValue("pageIndex"); index != "" {
		pageIndex = tools.StrToInt(err, index)
	}

	if index := c.Request.FormValue("courseId"); index != "" {
		data.CourseId = tools.StrToInt(err, index)
	}
	if index := c.Request.FormValue("organId"); index != "" {
		data.OrganId = tools.StrToInt(err, index)
	}
	data.CourseStatus = c.Request.FormValue("courseStatus")
	data.CourseName = c.Request.FormValue("courseName")
	data.CourseImg = c.Request.FormValue("courseImg")
	data.CourseType = c.Request.FormValue("courseType")
	data.CourseCategory = c.Request.FormValue("courseCategory")
	data.OrganName = c.Request.FormValue("organName")
	data.BrandName = c.Request.FormValue("brandName")
	data.CourseTeach = c.Request.FormValue("courseTeach")
	if index := c.Request.FormValue("coursePrice"); index != "" {
		data.CoursePrice = tools.StringToFloat64(err, index)
	}
	if index := c.Request.FormValue("discountPrice"); index != "" {
		data.DiscountPrice = tools.StringToFloat64(err, index)
	}
	data.CourseTime = c.Request.FormValue("courseTime")
	data.CourseAge = c.Request.FormValue("courseAge")
	data.UpdateStart = c.Request.FormValue("updateStart")
	data.UpdateEnd = c.Request.FormValue("updateEnd")

	data.DataScope = tools.GetUserIdStr(c)
	result, count, err := data.GetFiancePage(pageSize, pageIndex) // 下载
	if err != nil {
		app.ApiResp(c, -1, "数据操作失败："+err.Error(), nil)
		return
	}

	header := []string{"品牌名", "机构名", "课程名", "平台销量", "退费金额", "销售总额"} //标题
	cellist := [][]string{
		header,
	}
	cellist = DataToStringV7(result, cellist)

	page := count/pageSize + 1

	for i := 2; i <= page; i++ {
		pageIndex = i
		result, _, _ = data.GetFiancePage(pageSize, pageIndex) // 下载
		if len(result) <= 0 {
			break
		}
		cellist = DataToStringV7(result, cellist)
	}

	// 创建文件
	filepath := "static/"
	filename := "FianceOrganCourse_" + time.Now().Format("20060102150405") + ".csv"
	newFile, err := os.Create(filepath + filename)
	if err != nil {
		app.OK(c, nil, err.Error())
		return
	}
	defer func() {
		newFile.Close()

		err := os.Remove(filepath + filename)
		if err != nil {
			// 删除失败
			lognew.Info(c, "导出文件-清理失败", lognew.Fields{"file": filepath + filename, "err": err.Error()})
		}

	}()

	// 写入UTF-8
	newFile.WriteString("\xEF\xBB\xBF") // 写入UTF-8 BOM，防止中文乱码
	// 写数据到csv文件
	w := csv.NewWriter(newFile)
	// WriteAll方法使用Write方法向w写入多条记录，并在最后调用Flush方法清空缓存。
	w.WriteAll(cellist)
	w.Flush()

	c.File(filepath + filename)

}

// "品牌名", "机构名", "课程名", "平台销量", "退费金额", "销售总额"
func DataToStringV7(list []models.CourseNew, data [][]string) [][]string {
	for i := 0; i < len(list); i++ {
		context := []string{
			list[i].BrandName,
			list[i].OrganName,
			list[i].CourseName,
			tools.IntToString(list[i].CourseOrderNum),
			tools.Float64ToStringV2(list[i].CourseOrderSureRefund),
			tools.Float64ToStringV2(list[i].CourseOrderSurePrice),
		}
		data = append(data, context)
	}
	return data
}
